<template>
    <div class="filterConfig">
        <el-form :model="form" ref="filterForm" size="small" inline label-position="top">
            <Draggable v-model="form.filters" force-fallback="true" animation="300">
                <transition-group>
                    <div class="filter-item" v-for="(filter,index) in form.filters" :key="filter.key">
                        <el-form-item
                            :rules="rules.fieldName"
                            :prop="`filters.${index}.fieldName`"
                            label="查询条件名称">
                            <el-input v-model="filter.fieldName" placeholder="默认使用关联字段中文名"></el-input>
                        </el-form-item>
                        <el-form-item
                            :rules="rules.filterComType"
                            :prop="`filters.${index}.filterComType`"
                            label="控件类型">
                            <el-input v-model="filter.filterComType" @click.native="showCtrlComponent(index)" readOnly
                                      placeholder="请选择" style="cursor: pointer"></el-input>
                        </el-form-item>
                        <el-form-item
                            :rules="rules.linkField"
                            :prop="`filters.${index}.linkField`"
                            label="关联字段">
                            <el-select v-model="filter.linkField" :loading="!allFieldLoaded">
                                <el-option v-for="option in allFields"
                                           :key="option.enName"
                                           :label="option.name"
                                           :value="option.enName">
                                    <div class="select-option">
                                        <span>{{option.name}}</span>
                                        <span>{{option.enName}}</span>
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="_" class="delete-btn">
                            <el-button @click="remove(index)" type="danger" plain>删除</el-button>
                        </el-form-item>
                    </div>
                </transition-group>
            </Draggable>

        </el-form>
        <div class="btn-group">
            <div>
                <el-button @click="add">新增查询条件</el-button>
                <el-button @click="validate" type="primary">保存</el-button>
            </div>
            <el-button @click="handleDelete" type="primary" plain>全部删除</el-button>
        </div>
        <FilterCtrlType :visible="showCtrlType"
                        :dataValue="currentFilterComOptions"
                        @cancel="showCtrlType = false"
                        @save="ctrlChange"/>
    </div>
</template>

<script>
    import FilterCtrlType from "./components/FilterCtrlType";
    import {MessageBox} from "element-ui";
    import Draggable from 'vuedraggable'
    import {ADD_MODEL_COL, DELETE_MODEL_COL, GET_MODEL_COL, UPDATE_COMMON, UPDATE_MODEL_COL} from "../../../api/url";

    const MockData = [
        {
            filterComType: 'Input',
            filterComOptions: {
                placeholder: '请输入'
            },
            name: '姓名',
            linkField: 'userName',
            sort: 0
        },
        {
            filterComType: 'Select',
            filterComOptions: {
                placeholder: '请选择',
                options: [
                    {name: '男', value: 1},
                    {name: '女', value: 2},
                ]
            },
            name: '性别',
            linkField: 'sex',
            sort: 1
        },
        {
            filterComType: 'DatePicker',
            filterComOptions: {
                placeholder: '请选择日期',
            },
            name: '订单日期',
            linkField: 'createDate',
            sort: 2
        }
    ]

    /**
     * 筛选条件配置界面
     */
    export default {
        name: "FilterConfigIndex",
        components: {FilterCtrlType, Draggable},
        data() {
            return {
                isUpdate:false, // 是否是编辑
                filterObject: {
                    filterComType: '',// 组件类型
                    linkField: '', // 关联字段
                    fieldName: '', // 字段名
                    sort: '', // 排序
                },
                form: {
                    filters: []
                },
                rules: {
                    filterComType: [
                        {required: true, message: '控件类型不能为空'},
                    ],
                    linkField: [
                        {required: true, message: '连接字段不能为空'},
                    ],
                    fieldName: [
                        {required: true, message: '查询条件名称不能为空'},
                    ]
                },
                showCtrlType: false,
                curIndex: 0,
                unitId: '',
                allFieldLoaded: false,
                allFields: [
                    {
                        name: '姓名',
                        enName: 'userName',
                    },
                    {
                        name: '性别',
                        enName: 'sex',
                    },
                    {
                        name: '订单日期',
                        enName: 'orderDate',
                    }]
            }
        },
        computed: {
            // 当前进行的过滤组件配置数据
            currentFilterComOptions() {
                const temp = this.form.filters[this.curIndex]
                if (temp) {
                    return {
                        type: temp.filterComType,
                        ...temp.filterComOptions
                    }
                }
                return null
            },
            tempArr() {
                return this.form.filters || []
            }
        },
        mounted() {
            const {unitId} = this.$route.query
            if (unitId) {
                this.unitId = unitId
                this.queryFilterConfig()
                this.queryAllLinkFields()
            }
        },
        methods: {
            handleDelete(){
                MessageBox.confirm('确定删除所有查询条件吗？').then(() => {
                    this.$http.post(DELETE_MODEL_COL, {modelId: this.unitId}).then(res =>{
                        this.form.filters = []
                        MessageBox.alert(res.data.data)
                    })
                })
            },
            queryAllLinkFields() {
                this.$http.post(UPDATE_COMMON, {type: '1', unitId: this.unitId}).then(res => {
                    const {fields} = res.data.body
                    this.allFields = fields.map(item => {
                        return {
                            enName: item.name,
                            name: item.value
                        }
                    })
                }).finally(() => this.allFieldLoaded = true)
            },
            queryFilterConfig() {
                this.$http.post(GET_MODEL_COL,{modelId:this.unitId}).then(res => {
                    const {data:{data}} = res
                    if(!data) return
                    this.isUpdate = true
                    if(data.formula){
                        this.form.filters = JSON.parse(data.formula)
                    }
                })
            },
            add() {
                const temp = JSON.parse(JSON.stringify(this.filterObject))
                this.form.filters.push(Object.assign(temp, {key: Date.now()}))
            },
            validate() {
                if (this.form.filters.length === 0) {
                    return MessageBox.alert('请添加过滤条件！')
                }
                this.$refs.filterForm.validate((e) => {
                    if (e) {
                        this.save()
                    }
                })
            },
            save() {
                const {unitId, boardId} = this.$route.query
                const filters = [
                    ...this.form.filters.map((item, i) => {
                        return {...item, sort: i + 1}
                    })
                ]
                const url = this.isUpdate?UPDATE_MODEL_COL:ADD_MODEL_COL
                this.$http.post(url,{formula:JSON.stringify(filters),modelId:unitId}).then(res => {
                    MessageBox.alert(res.data.data)
                })
            },
            remove(index) {
                MessageBox.confirm('确定删除该查询条件吗？').then(() => {
                    this.form.filters.splice(index, 1);
                })
            },
            showCtrlComponent(index) {
                this.curIndex = index
                this.showCtrlType = true
            },
            ctrlChange(e) {
                this.showCtrlType = false
                const {type, ...options} = e // 解构出组件类型反显，其他属性不显示，但是要保存
                this.form.filters[this.curIndex].filterComType = type
                this.form.filters[this.curIndex].filterComOptions = {...options}
            }
        }
    }
</script>

<style scoped lang="stylus">
    .select-option {
        display flex
        justify-content space-between

        span:last-child {
            font-size 13px
            color #8492a6
            margin-left 20px
        }
    }

    .filterConfig >>> {
        background-color white
        padding 15px

        .filter-item {
            border-bottom 1px dashed #454545
            margin-bottom 10px
            &:hover {
                cursor all-scroll
                user-select none
            }

        }

        .el-form-item {
            &.delete-btn {
                .el-form-item__label {
                    color transparent
                }
            }

            .el-form-item__label {
                line-height unset !important
                padding 0 !important
            }
        }
        .btn-group{
            display flex
            justify-content space-between
            margin-top 20px
        }
    }

</style>
